package cn.middle.swap.portal;

import javax.validation.constraints.NotBlank;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.middle.common.result.ApiResponse;
import com.middle.common.result.UserInfo;

import cn.dev33.satoken.annotation.SaCheckLogin;
import cn.dev33.satoken.annotation.SaIgnore;
import cn.dev33.satoken.stp.StpUtil;
import cn.middle.basic.entity.SysMenu;
import cn.middle.basic.entity.SysRole;
import cn.middle.basic.entity.SysUser;
import cn.middle.basic.service.SysUserService;

@Controller
public class LoginController {

	private final Logger logger = LoggerFactory.getLogger(this.getClass());

	@Autowired
	private SysUserService userService;

	@SaIgnore
	@GetMapping("/login")
	public String login() {
		//已登陆，直接跳转到index界面
		if(StpUtil.isLogin()) {
			return "redirect:index";
		}
		return "login";
	}
	/**
	 * 登陆
	 * @param username
	 * @param password
	 * @return
	 */
	@SaIgnore
	@SuppressWarnings("unchecked")
	@ResponseBody
	@RequestMapping("/doLogin")
	public ApiResponse<UserInfo<SysMenu,SysRole>> doLogin(@NotBlank(message="登陆名不能为空！")String username,@NotBlank(message="密码不能为空！") String password) {
		
		SysUser sysUser = userService.login(username, password);
		if (sysUser != null) {
			StpUtil.login(sysUser.getId());
			UserInfo<SysMenu,SysRole> userInfo = userService.getUserInfo(sysUser.getId());
			logger.info("{} 登陆成功!", username);
			return ApiResponse.successWithData(userInfo);
		}
		return ApiResponse.LOGIN_USERPASSWORD_ERROR;
	}
	
	/**
	 * 获取用户信息
	 * @return
	 */
	@SuppressWarnings("unchecked")
	@SaCheckLogin
	@ResponseBody
	@GetMapping("/getUserInfo")
	public ApiResponse<UserInfo<SysMenu,SysRole>> getUserInfo(){
		Long loginId = loginId();
		UserInfo<SysMenu,SysRole> userInfo = userService.getUserInfo(loginId);
		if(userInfo == null) {
			return ApiResponse.FailCustomWithMessage(String.valueOf(-1000), "用户信息不存在！");
		}
		return ApiResponse.successWithData(userInfo);
	}
	
	/**
	 * 注销登陆
	 */
	@SaCheckLogin
	@GetMapping("/logout")
	public String doLoginOut() {
		StpUtil.logout();
		return "redirect:/login";
	}
	
	public Long loginId() {
		Object objectId = StpUtil.getLoginId();
		if(objectId instanceof String) {
			return Long.parseLong((String)objectId);
		}else if(objectId instanceof Long) {
			return (Long) objectId;
		}
		return Long.parseLong(objectId.toString());
	}

}
